/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.model.command;

import static com.cea.papyrus.diagram.sequence.sedi.model.util.ModelUtil.getBodies;

import java.util.List;

import org.eclipse.gef.commands.Command;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.OpaqueExpression;
import org.eclipse.uml2.uml.StateInvariant;

/**
 * Command to set the constraint on a StateInvariant.
 * 
 * <p>
 * <b>Known limitations</b> The current implementation always updates body #0.
 * The constraint is not parsed in any way but assigned as an OpaqueExpression
 * string.
 * </p>
 * 
 * <p>
 * The following attributes must be set for the command to complete
 * successfully:
 * </p>
 * <ul>
 * <li>StateInvariant
 * <li>ExpressionString
 * </ul>
 * 
 * @author frankd@ifi.uio.no
 */
public class SetStateInvariantCommand extends Command {

	private StateInvariant stateInvariant;
	private String expressionString, oldExpressionString;

	public void setStateInvariant(final StateInvariant stateInvariant) {
		this.stateInvariant = stateInvariant;
	}

	public void setExpressionString(String expressionString) {
		this.expressionString = expressionString;
	}

	@Override
	public void execute() {
		Constraint constraint = stateInvariant.getInvariant();
		if (constraint != null
				&& constraint.getSpecification() instanceof OpaqueExpression) {
			OpaqueExpression expr = (OpaqueExpression) constraint
					.getSpecification();
			List<String> exprBodies = getBodies(expr);
			if (!exprBodies.isEmpty())
				oldExpressionString = exprBodies.get(0);
			exprBodies.set(0, expressionString);
		}
		// TODO Handle other expressions, and/or log when there are problems
	}

	@Override
	public void undo() {
		Constraint constraint = stateInvariant.getInvariant();
		if (constraint != null
				&& constraint.getSpecification() instanceof OpaqueExpression) {
			OpaqueExpression expr = (OpaqueExpression) constraint
					.getSpecification();
			getBodies(expr).set(0, oldExpressionString);
		}
		oldExpressionString = null;
	}

	@Override
	public void redo() {
		this.execute();
	}

	@Override
	public void dispose() {
		stateInvariant = null;
		expressionString = null;
		oldExpressionString = null;
	}
}
